package com.yt.app.api.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.yt.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 上传图片类
 * 
 * @author java
 * 
 */
public class UploadImageUtils {

    private static final Logger logger = LoggerFactory.getLogger(UploadImageUtils.class);


    private static SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
	/**
	 * 生成10位随机数
	 * 
	 * @return
	 */
	public static String getRandomNum() {
		return MD5Util.MD5(System.currentTimeMillis() + "").substring(0, 10);
	}
	
	private static OSSClient getClient() {
		return new OSSClient(Config.OSS_END_POINT, Config.OSS_ACCESS_ID, Config.OSS_ACCESS_KEY);
	}
	
	public static boolean isFileExists(String folderName, String fileName) {
		boolean isExist = false;
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(Config.OSS_BUCKET_NAME);
		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");
		// 列出fun目录下的所有文件和文件夹
		listObjectsRequest.setPrefix(folderName);
		ObjectListing listing = getClient().listObjects(listObjectsRequest);
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			if (objectSummary.getKey().endsWith(fileName)) {
				isExist = true;
				break;
			}
		}
		return isExist;
	}
	
	/**
	 * 上传图片，返回图片的路径
	 * 
	 * @param folderName
	 * @param fileName
	 * @param is
	 * @param isOld
	 * @return
	 */
	public static String saveObject(String folderName, String fileName, InputStream is, boolean isOld, boolean isPublic) {
		// 如果是新添加的图片，则需要判断数据库是否存在相同的图片
		if (!isOld) {
			boolean isExit = false;
			do {
				isExit = isFileExists(folderName, fileName);
				if (isExit) {
					// 保存路径
					Calendar cal = Calendar.getInstance();
					StringBuffer sb = new StringBuffer();
					sb.append("activity").append("/");
					sb.append(cal.get(Calendar.YEAR)).append("/");
					sb.append((cal.get(Calendar.MONTH) + 1) > 9 ? (cal.get(Calendar.MONTH) + 1) : "0" + (cal.get(Calendar.MONTH) + 1)).append("/");
					sb.append(cal.get(Calendar.DATE) > 9 ? cal.get(Calendar.DATE) : "0" + cal.get(Calendar.DATE)).append("/");
					folderName = sb.toString();
					// 文件名
					String fileExt = fileName.substring(fileName.length() - 4);
					fileName = UploadImageUtils.getRandomNum() + fileExt;
				}
			} while (isExit);
		}
		// !!相同名称会覆盖
		String resulut = null;
		try {
			ObjectMetadata objectMeta = new ObjectMetadata();
			objectMeta.setContentLength(is.available());
			PutObjectResult result = getClient().putObject(isPublic?Config.OSS_BUCKET_NAME:Config.OSS_PRIVATE_BUCKET_NAME, folderName + fileName, is, objectMeta);
			resulut = folderName + fileName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			}
		}
		return resulut;
	}
	
	/**
	 * 上传文件
	 * 
	 * @param pic
	 * @param folder
	 * @return
	 */
	public static  String uploadImage(MultipartFile pic, String folder, boolean isPublic) {
		try {
			if (pic != null && pic.getSize() > 0) {
				String fileName = null;
				String path = null;
				boolean isOld = false;
				// 保存路径
				Calendar cal = Calendar.getInstance();
				StringBuffer sb = new StringBuffer();
				if(!"pro".equals(Config.env)) {
					sb.append(Config.env).append("/");
				}
				sb.append(folder == null ? "" : folder).append("/");
				sb.append(cal.get(Calendar.YEAR)).append("/");
				sb.append((cal.get(Calendar.MONTH) + 1) > 9 ? (cal.get(Calendar.MONTH) + 1) : "0" + (cal.get(Calendar.MONTH) + 1)).append("/");
				sb.append(cal.get(Calendar.DATE) > 9 ? cal.get(Calendar.DATE) : "0" + cal.get(Calendar.DATE)).append("/");
				path = sb.toString();
				// 文件名
				String fileExt = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
				fileName = UploadImageUtils.getRandomNum() + fileExt.toLowerCase();
				String result = saveObject(path, fileName, pic.getInputStream(), isOld, isPublic);
				if (StringUtils.isNotEmpty(result)) {
					return result;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getPrivateUrl(String url, int expireInSecond){
		Date expires = new Date (System.currentTimeMillis() + 1000 * expireInSecond);
		url = url.replace(Config.private_image_url + "/", "");
		GeneratePresignedUrlRequest generatePresignedUrlRequest =
				new GeneratePresignedUrlRequest(Config.OSS_PRIVATE_BUCKET_NAME, url);
		generatePresignedUrlRequest.setExpiration(expires);
		return getClient().generatePresignedUrl(generatePresignedUrlRequest).toExternalForm();
	}
}
